package com.ruoyi.back.ct.service;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Date;
import java.util.List;
import java.util.Map;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.ruoyi.back.ct.domain.CtAgreementTpl;
import com.ruoyi.back.ct.mapper.CtAgreementTplMapper;
import com.ruoyi.back.oa.domain.OaCustomFormApply;
import com.ruoyi.back.oa.service.FlowProcessInstanceService;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.constant.BillTypeEnum;
import com.ruoyi.common.constant.CommonConstants;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.util.FlowUtil;
import com.ruoyi.common.util.OfficeUtil;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.system.mapper.SysUserMapper;
import org.flowable.engine.HistoryService;
import org.flowable.engine.RuntimeService;
import org.flowable.engine.runtime.ProcessInstance;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.back.ct.mapper.CtAgreementMapper;
import com.ruoyi.back.ct.domain.CtAgreement;
import org.springframework.transaction.annotation.Transactional;

/**
 * 补充协议Service业务层处理
 * 
 * @author pointLion
 * @date 2023-05-13
 */
@Service
public class CtAgreementService
{
    @Autowired
    private CtAgreementMapper ctAgreementMapper;
    @Autowired
    private CtAgreementTplMapper ctAgreementTplMapper;
    @Autowired
    private RuntimeService runtimeService;
    @Autowired
    private HistoryService historyService;
    @Autowired
    private FlowProcessInstanceService flowProcessInstanceService;
    @Autowired
    private SysUserMapper sysUserMapper;
    @Autowired
    private CtAgreementService ctAgreementService;

    /**
     * 查询补充协议
     * 
     * @param id 补充协议主键
     * @return 补充协议
     */
    public CtAgreement selectCtAgreementById(Long id)
    {
        return ctAgreementMapper.selectCtAgreementById(id);
    }

    /**
     * 查询补充协议列表
     * 
     * @param ctAgreement 补充协议
     * @return 补充协议
     */
    public List<CtAgreement> selectCtAgreementList(CtAgreement ctAgreement)
    {
        List<CtAgreement> list = ctAgreementMapper.selectCtAgreementList(ctAgreement);
        for(CtAgreement a:list){
            a.setIfNotice(DateUtil.compare(a.getByTime(),DateUtils.parseDate(DateUtils.getDate())));
        }
        return list;
    }

    /**
     * 新增补充协议
     * 
     * @param ctAgreement 补充协议
     * @return 结果
     */
    public int insertCtAgreement(CtAgreement ctAgreement)
    {
        ctAgreement.setCreateTime(DateUtils.getNowDate());
        return ctAgreementMapper.insertCtAgreement(ctAgreement);
    }

    /**
     * 修改补充协议
     * 
     * @param ctAgreement 补充协议
     * @return 结果
     */
    public int updateCtAgreement(CtAgreement ctAgreement)
    {
        ctAgreement.setUpdateTime(DateUtils.getNowDate());
        return ctAgreementMapper.updateCtAgreement(ctAgreement);
    }

    /**
     * 批量删除补充协议
     * 
     * @param ids 需要删除的补充协议主键
     * @return 结果
     */
    public int deleteCtAgreementByIds(Long[] ids)
    {
        return ctAgreementMapper.deleteCtAgreementByIds(ids);
    }

    /**
     * 删除补充协议信息
     * 
     * @param id 补充协议主键
     * @return 结果
     */
    public int deleteCtAgreementById(Long id)
    {
        return ctAgreementMapper.deleteCtAgreementById(id);
    }


    /*****
     * 预览
     * @param id
     * @return
     */
    public String buildAgreementContent(Long id){
        CtAgreement agreement = ctAgreementMapper.selectCtAgreementById(id);

        String content = buildContent(agreement);

        return content;
    }

    private String buildContent(CtAgreement agreement ){
        String content = "";
        CtAgreementTpl tpl = ctAgreementTplMapper.selectCtAgreementTplById(agreement.getTplId());
        if(tpl!=null){
            content = tpl.getContent();
            Field[] fields = agreement.getClass().getDeclaredFields();
            for(Field f:fields){
                String fieldName = f.getName();
                String name = fieldName.substring(0,1).toUpperCase()+fieldName.substring(1);
                try {
                    if(!"serialVersionUID".equals(fieldName)){
                        Method m = agreement.getClass().getMethod("get"+name);
                        Object obj =  m.invoke(agreement);
                        if(obj!=null){
                            content = content.replace("{{"+f.getName()+"}}",obj.toString());
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }

        return content;
    }

    /*****
     * 生成文件
     */
    public void buildFile(Long id) throws Exception {
        CtAgreement agreement = ctAgreementMapper.selectCtAgreementById(id);
        String content = buildContent(agreement);
        String path = RuoYiConfig.getProfile()+"/office/ct";
        File folder = new File(path);
        if(!folder.exists()){
            folder.mkdirs();
        }
        String rPath = "/office/ct/"+agreement.getContractName()+".doc";
        String realPath = RuoYiConfig.getProfile()+rPath;
        OfficeUtil.createWordByHtml(content,realPath);
        agreement.setUrl(Constants.RESOURCE_PREFIX+rPath);
        ctAgreementMapper.updateCtAgreement(agreement);
    }


    /****
     * 提交流程
     * @param id
     */
    @Transactional
    public void submitFlow(Long id){
        CtAgreement agreement = ctAgreementMapper.selectCtAgreementById(id);
        ProcessInstance procIns = flowProcessInstanceService.startProcess(id,agreement.getContractName(), BillTypeEnum.AGREEMENT.getBillType());
        CtAgreement updateAgreement = new CtAgreement();
        updateAgreement.setId(agreement.getId());
        updateAgreement.setFlowInsId(procIns.getId());
        updateAgreement.setFlowKey(BillTypeEnum.AGREEMENT.getDefKey());
        updateAgreement.setFlowName(procIns.getProcessDefinitionName());
        updateAgreement.setStatus(CommonConstants.FLOW_STATUS_SUBMIT);//更新状态
        updateAgreement.setUpdateTime(new Date());
        updateAgreement.setSubmitTime(new Date());
        ctAgreementMapper.updateCtAgreement(updateAgreement);
    }





    /****
     * 取回流程
     * @param id
     */
    public void cancleFlow(Long id){
        CtAgreement agreement = ctAgreementMapper.selectCtAgreementById(id);
        String insId = agreement.getFlowInsId();
        if(StrUtil.isNotBlank(insId)){
            flowProcessInstanceService.cancleProcesInstance(insId,"用户撤销");
        }
        CtAgreement updateAgreement = new CtAgreement();
        updateAgreement.setId(id);
        updateAgreement.setStatus(CommonConstants.FLOW_STATUS_START);
        updateAgreement.setFlowInsId("");
        updateAgreement.setFlowKey("");
        updateAgreement.setFlowName("");
        updateAgreement.setUpdateTime(new Date());
        ctAgreementMapper.updateCtAgreement(updateAgreement);
    }
}
